package com.telsoft.hms.data;

import java.util.ArrayList;
import java.util.List;

import com.telsoft.hms.entity.ETT_Bookmark;
import com.telsoft.hms.lib.admin.client.data.ClientDataPreprocessor;

public class DATA_Bookmark extends ClientDataPreprocessor {
	/**
	 * @author NinhNV
	 * @param lUserId: Mã người dùng
	 * @param strHospitalKey: Mã bệnh viện để kết nối CSDL
	 * @return ETT_Bookmark[] Mảng danh sách bookmark
	 * @throws Exception
	 * Ngày tạo 07/10/2014
	 */
	public ETT_Bookmark[] getAllBookmark(long lUserId, String strHospitalKey)
			throws Exception {
		String strSql = "SELECT \"VALUES\" FROM AM_CONFIG WHERE LOWER(TYPE) = LOWER('BOOKMARK') AND USER_ID = ?";
		List<ETT_Bookmark> lstBookmark = new ArrayList<ETT_Bookmark>();
		try {
			open(strHospitalKey);
			mStmt = mConnection.prepareStatement(strSql);
			mStmt.setLong(1, lUserId);
			mRs = mStmt.executeQuery();
			while (mRs.next()) {
				String values = mRs.getString("VALUES");
				String[] valuesTmp = values.split(":");
				if (valuesTmp.length > 1) {
					ETT_Bookmark bookmark = new ETT_Bookmark();
					bookmark.setName(valuesTmp[0]);
					bookmark.setPath(valuesTmp[1]);
					lstBookmark.add(bookmark);
				}
			}
		} catch (Exception e) {
			throw e;
		}finally{
			close(mRs);
			close(mStmt);
			close(mConnection);
		}
		return lstBookmark.toArray(new ETT_Bookmark[lstBookmark.size()]);
	}
	/**
	 * @author NinhNV
	 * @param lUserId: Mã người dùng
	 * @param strHospitalKey: Mã bệnh viện để kết nối CSDL
	 * @param strPath: Đường dẫn bookmark
	 * @throws Exception
	 * Ngày tạo 07/10/2014
	 */
	public int deleteBookmark(long lUserId, String strHospitalKey, String strPath) throws Exception{
		int iResult = 0;
		String strSql = "DELETE FROM AM_CONFIG WHERE LOWER(TYPE) = LOWER('BOOKMARK') AND USER_ID = ? AND \"VALUES\" LIKE ?";
		try {
			open(strHospitalKey);
			mStmt = mConnection.prepareStatement(strSql);
			mStmt.setLong(1, lUserId);
			mStmt.setString(2, "%" + strPath);
			iResult = mStmt.executeUpdate();
		} catch (Exception e) {
			throw e;
		}finally{
			close(mStmt);
			close(mConnection);
		}
		return iResult;
	}
	/**
	 * @author NinhNV
	 * @param lUserId: Mã người dùng
	 * @param strHospitalKey: Mã bệnh viện để kết nối CSDL
	 * @param bookmark: Đối tượng bookmark thêm vào CSDL
	 * @throws Exception
	 * Ngày tạo 08/10/2014
	 */
	public int addBookmart(long lUserId, String strHospitalKey, ETT_Bookmark objBookmark)throws Exception{
		int iResult = 0;
		String strSql = "INSERT INTO AM_CONFIG VALUES (?,?,?)";
		try {
			open(strHospitalKey);
			mStmt = mConnection.prepareStatement(strSql);
			mStmt.setLong(1, lUserId);
			mStmt.setString(2, "BOOKMARK");
			mStmt.setString(3,objBookmark.getName() + ":" + objBookmark.getPath());
			
			iResult=mStmt.executeUpdate();
		} catch (Exception e) {
			throw e;
		}finally{
			close(mStmt);
			close(mConnection);
		}
		return iResult;
	}
}
